package cz.anime.ppro.logic;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import cz.anime.ppro.enums.UserRolesEnum;
import cz.anime.ppro.model.Webuser;
import cz.anime.ppro.repositories.UserRepository;


@Component
public class UserComponentImpl implements UserComponent{
	
	@Autowired
	private UserRepository userRepository;

	@Override
	public List<Webuser> getUsers() {
		return userRepository.findAll();
	}
	
	@Override
	public Webuser getUser(int id) {
		return userRepository.findWebuserById(id);
	}

	@Override
	public void createUser(Webuser user) {
		userRepository.saveAndFlush(user);
	}
	
	@Override
	public Webuser getUserByNick(String nick) {
		return userRepository.findWebuserByNick(nick);
	}
	
	@Override
	public void save(Webuser user) {
		userRepository.saveAndFlush(user);
	}
	
	@Override
	public void delete(Webuser user) {
		userRepository.delete(user);
	}

	@Override
	public String getCurrentUsernameFromSession() {		
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		if (auth != null) {
			if (auth.getName().equals("anonymousUser")) {
				return "Anonymous";
			} else {
				return auth.getName();
			}
		}else{
			return "Anonymous";
		}
	}

	@Override
	public boolean hasCurrentUserAdminRole() {
		return UserRolesEnum.ROLE_ADMIN.name().equals(getUserByNick(getCurrentUsernameFromSession()).getRole());		
	}
	
}
